package org.steven.crm.core.auth;

import org.steven.crm.core.auth.dto.GrantTokenRequest;
import org.steven.crm.core.exception.BusinessErrors;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.accesstoken.AccessTokenService;
import org.steven.crm.core.service.systemuser.SystemUserService;
import com.steven.common.utils.MD5Util;

import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/10 17:31
 * @Version 1.0
 */
public class SystemUserAuthHandler extends AuthHandler {
    private static SystemUserService systemUserService = new SystemUserService();

    private static AccessTokenService accessTokenService = new AccessTokenService();

    @Override
    public Map<String, String> createToken(Map<String, String> client, GrantTokenRequest grantTokenRequest) throws Exception {
        Map<String, String> user = systemUserService.readByUserName(grantTokenRequest.getUsername());
        if (user.isEmpty() || user.get("validFlag").equals("0")) {
            throw new ServiceException(BusinessErrors.USER_NOT_FOUND);
        }

        if (!MD5Util.MD5(grantTokenRequest.getCode()).equals(user.get("password"))) {
            throw new ServiceException(BusinessErrors.USER_ERROR_PWD);
        }

        return accessTokenService.create(client.get("id"), user.get("id"));
    }

    @Override
    protected Map<String, String> authorize(Map<String, String> accessToken)  throws Exception {
        Map<String, String> user = systemUserService.read(accessToken.get("userId"));
        if (user.isEmpty() || user.get("validFlag").equals("0")) {
            throw new ServiceException(BusinessErrors.USER_NOT_FOUND);
        }

        return user;
    }
}
